<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>防抖与节流函数</title>

</head>

<body>
    <label for="submit">
        <input type="text" id="submit">
    </label>
    <button>提交</button>

    <script>
        // 获取元素
        const btn = document.querySelector('button');
        // 绑定事件
        // 防抖完整版
        btn.addEventListener('click', throttle(sub, 300, ture));
        // 防抖精简版
        btn.addEventListener('click', throttle(sub, 300));
        // 节流
        btn.onclick = throttle(move, 1000);

        function move(e) {
            console.log(1)
        }
        // ---------------节流函数---------------------
        function throttle(func, delay) {
            let beginTime = 0;
            return function(...args) {
                let timer = +new Date();
                if (timer - beginTime > delay) {
                    func.apply(this, args);
                    beginTime = timer;
                }
            }
        }
        // ---------------防抖函数---------------------

        function debounce(func, wait) {
            let timer = null;
            return function(...args) {
                if (timer) clearTimeout(timer);
                timer = setTimeout(() => {
                    func.apply(this, args)
                }, wait)
            }
        }

        // 完整版
        function debounce(func, wait, now) {
            let timer = null;
            return function(...args) {
                if (timer) clearTimeout(timer);
                if (now) {
                    let first = !timer;
                    if (first) func.apply(this, args);
                    timer = setTimeout(() => {
                        timer = null;
                    }, wait)
                } else {
                    timer = setTimeout(() => {
                        func.apply(this, args)
                    }, wait)
                }

            }
        };
        // 精简版
        function debounce(func, wait, now) {
            let timer = null;
            return function(...args) {
                let first = !timer;
                if (timer) clearTimeout(timer);
                if (first) func.apply(this, args);
                timer = setTimeout(() => {
                    timer = null;
                }, wait)
            }
        };
    </script>
</body>

</html>